package com.avantis.admin.service.impl;

import com.avantis.admin.service.RedisService;
import com.avantis.admin.service.UserService;
import com.avantis.common.base.BaseServiceImpl;
import com.avantis.common.exception.ServiceProcessException;
import com.avantis.common.repository.UserRepository;
import com.avantis.common.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.persistence.criteria.*;
import java.util.*;

@Service
public class UserServiceImpl extends BaseServiceImpl<UserRepository, User> implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RedisService<Integer> redisSocketService;

    @Autowired
    private RedisService<User> redisService;

    private String REDIS_USERID_KEY;

    private String REDIS_USER_KEY;

    private Integer REDIS_USER_TIME;


    @Override
    public Page<User> findByPage(User user, Integer pageNo, Integer length) {
        PageRequest pageable =  PageRequest.of(pageNo, length);

        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<Integer> $id = root.get("id");
                Path<String> $username = root.get("username");
                Path<String> $email = root.get("email");
                Path<Integer> $enable = root.get("enable");

                ArrayList<Predicate> list = new ArrayList<>();
                if (user.getId() != null) list.add(criteriaBuilder.equal($id, user.getId()));
                if (user.getEnable() != null) list.add(criteriaBuilder.equal($enable, user.getEnable()));
                if (user.getUserName() != null)
                    list.add(criteriaBuilder.like($username, "%" + user.getUserName() + "%"));

                Predicate predicate = criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
                return predicate;
            }
        };
        Page<User> page = userRepository.findAll(specification, pageable);

        return page;
    }

    @Override
    public void saveUserEnable(Integer[] id) {
        //List<User> all = findAll(Arrays.asList(id));
        List<User> all = findAll();
        for (User user :all) {
            if (user.getEnable() == 1) {
                user.setEnable(0);
            } else {
                user.setEnable(1);
            }
            save(user);
        }
    }

    @Override
    public boolean checkUserName(String username) {
        User user = userRepository.findByUserName(username);
        if (user == null) return true;
        return false;
    }

    @Override
    public boolean checkUserEmail(String email) {
        User user = userRepository.findByEmail(email);
        if (user == null) return true;
        return false;
    }

    @Override
    public User findByEmail(String email) {
        return userRepository.findByEmail(email);
    }

    @Override
    public void createUser(String email, String username, String password) {
        User user = new User();
        user.setEmail(email);
        user.setUserName(username);
        user.setInitTime(new Date());
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userRepository.save(user);
    }

    @Override
    public String LoginUser(User user) {
        String token = UUID.randomUUID().toString();
        redisService.cacheString(REDIS_USER_KEY + token, user, REDIS_USER_TIME);
//        redisSocketService.cacheSet(REDIS_USERID_KEY,user.getId());
//        loginId.add(user.getId());//维护一个登录用户的set
        return token;
    }

    @Override
    public User getUserByToken(String token) {
        User user = redisService.getStringAndUpDate(REDIS_USER_KEY + token, REDIS_USER_TIME);
        return user;
    }

    @Override
    public void LogoutUser(String token) {
        User user = getUserByToken(token);
        redisService.deleteString(REDIS_USER_KEY + token);
 //       redisSocketService.deleteSet(REDIS_USERID_KEY,user.getId());
//        loginId.remove(user.getId());//维护一个登录用户的set
    }

    @Override
    public void updateUser(String token, String username) {
        User cacheuser = redisService.getString(REDIS_USER_KEY + token);
        if (cacheuser == null) throw new ServiceProcessException("session过期,请重新登录");
//        User user = userRepository.findById(cacheuser.getId()).get();
//        user.setUserName(username);
//        userRepository.save(user);
//        redisService.cacheString(REDIS_USER_KEY + token, user, REDIS_USER_TIME);
    }

    @Override
    public void updateUserPassword(String token, String oldpsd, String newpsd) {
        User cacheuser = redisService.getString(REDIS_USER_KEY + token);
        if (cacheuser == null)
            throw new ServiceProcessException("用户Session过期，请重新登录");
//        User user = userRepository.findById(cacheuser.getId()).get();
//        if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(oldpsd.getBytes())))
//            throw new ServiceProcessException("原始密码错误,请重新输入");
//        user.setPassword(DigestUtils.md5DigestAsHex(newpsd.getBytes()));
//        userRepository.save(user);
//        redisService.deleteString(REDIS_USER_KEY+token);
    }
}
